﻿<%@ WebHandler Language="C#" Class="KMerWeb.Excel.PostHandler" %>

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using com.nm;
using com.nm.library.Excels;
using com.nm.library.Excels.Enums;
using com.nm.library.Excels.mime;
using com.nm.library.Excels.Mef;
using com.nm.library.HttpHelper;
using com.nm.library.Helper;
using george.Helper;
using Nancy;
using Newtonsoft.Json;
using VerticaAPI;
using VerticaAPI.model;

namespace KMerWeb.Excel
{
    /// <summary>
    /// Post一般处理程序的测试
    /// </summary>
    public class PostHandler : BaseHttpHandler
    {

        private static int num = 0;

        public PostHandler()
        {
            //修改请求为post 方式
            base._httpReuqest = base.Context.Request.Form;
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="strType"></param>
        public void ImportTemplate()
        {
            var result = new ImportResult();
            var strType = _httpReuqest.Get("filetype").ToUpper();
            var userId = _httpReuqest.Get("UserID") == null ? "0" : _httpReuqest.Get("UserID");
            try
            {
                if (AllImports == null)
                    AllImports = MefConfig.ResolveMany<ExcelImport>();
                //业务类型
                var type = EnumHelper.StringToEnum<ExcelImportType>(strType);
                //文件
                var file = Context.Request.Files[0];
                var handler = AllImports.FirstOrDefault(e => e.Type == type);
                if (handler == null)
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "未找到“" + type + "”相应处理模块";
                    result.Message = "未找到相应的处理模块";
                }
                result = handler.ImportTemplate(file.InputStream, file.FileName, Convert.ToInt16(userId));
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                output(result);
            }
            //result
            output(result);
        }

        /// <summary>
        /// 导入数据 参数订货货会内码ID
        /// 时间：2017-10-18
        /// 作者：曹亚亮
        /// </summary>
        /// <param name="context"></param>
        /// <param name="strType"></param>
        public void ImportTemplateMasterID()
        {
            var result = new ImportResult();
            var strType = _httpReuqest.Get("filetype").ToUpper();
            var userId = _httpReuqest.Get("UserID") == null ? "0" : _httpReuqest.Get("UserID");
            var MasterID = _httpReuqest.Get("MasterID");
            try
            {
                if (AllImports == null)
                    AllImports = MefConfig.ResolveMany<ExcelImport>();
                //业务类型
                var type = EnumHelper.StringToEnum<ExcelImportType>(strType);
                //文件
                var file = Context.Request.Files[0];
                var handler = AllImports.FirstOrDefault(e => e.Type == type);
                if (handler == null)
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "未找到“" + type + "”相应处理模块";
                    result.Message = "未找到相应的处理模块";
                }
                int num = 0;
                if (MasterID == null || !int.TryParse(MasterID, out num) || MasterID == "0")
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "订货会内码“" + MasterID + "”不正确";
                    result.Message = "订货会内码错误";
                }
                result = handler.ImportTemplate(file.InputStream, file.FileName, Convert.ToInt16(MasterID));
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                output(result);
            }
            //result
            output(result);
        }

        /// <summary>
        /// 导出Excel表格
        /// </summary>
        public void ExportExcel()
        {
            //var excelParam = _httpReuqest["excelParam"];
            var fileName = _httpReuqest.Get("FileName");
            var strtype = _httpReuqest.Get("Type");
            //获取查询参数
            var conditions = HttpContext.Current.Server.UrlDecode(_httpReuqest.Get("conditions"));
            List<VerticaAPI.model.SearchCondition> searchCondition = null;
            //判断conditions是否为空
            if (!string.IsNullOrWhiteSpace(conditions))
            {
                searchCondition = JsonConvert.DeserializeObject<List<VerticaAPI.model.SearchCondition>>(conditions);
            }
            if (string.IsNullOrEmpty(strtype))
            {
                Context.Response.Write("参数错误");
            }
            var json = new StringBuilder();
            json.Append("{\"FileName\":\"" + fileName + "\",\"Type\":\"" + strtype + "\"}");

            var info = JsonConvert.DeserializeObject<ExcelInfo>(json.ToString());
            if (AllImports == null)
                AllImports = MefConfig.ResolveMany<ExcelImport>();
            //业务类型
            var result = new ImportResult();
            var type = EnumHelper.StringToEnum<ExcelImportType>(info.Type.ToUpper());
            var handler = AllImports.FirstOrDefault(e => e.Type == type);
            if (handler == null)
            {
                result.IsSuccess = false;
                result.ExtraInfo = "未找到“" + type + "”相应处理模块";
                result.Message = "未找到相应的处理模块";
            }
            var keys = GetSearchCondition(searchCondition);
            var dt = handler.GetExportData(keys);
            if (dt.Rows.Count == 0)
            {
                result.IsSuccess = false;
                result.ExtraInfo = "未找到可导出的数据";
                result.Message = "无数据";
            }
            if (string.IsNullOrEmpty(info.FileName))
            {
                info.FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls";
            }
            else
            {
                if (!info.FileName.EndsWith(".xls"))
                {
                    info.FileName = info.FileName + ".xls";
                }
                var path = ExcelImporMapper.GetTemplatePath(type);
                var b = true;
                switch (type)
                {
                    case ExcelImportType.STATESKC:
                    case ExcelImportType.SECONDARYDATA:
                        b = false;
                        break;
                    default:
                        break;
                }
                MemoryStream ms = info.ExportExeclStream(dt, path, handler.DictFields, b);
                var msbyte = ms.GetBuffer();
                ms.Dispose();
                ms = null;
                try
                {
                    //var filePath = Path.GetFileName(path);
                    Context.Response.Buffer = true;
                    Context.Response.Clear();
                    Context.Response.ContentType = "application/msexcel";
                    Context.Response.AddHeader("Content-Disposition", "attachment;filename="
                                                                      +
                                                                      System.Web.HttpUtility.UrlPathEncode(info.FileName)
                                                                      + ";Content-Length=" + msbyte.Length);
                    Context.Response.BinaryWrite(msbyte); //返回文件数据给客户端下载
                    Context.Response.Flush();
                    Context.Response.End();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 导出Excel表格
        /// </summary>
        public void ExportExcelToDB()
        {
            try
            {
                //var excelParam = _httpReuqest["excelParam"];
                var fileName = _httpReuqest.Get("FileName");
                var strtype = _httpReuqest.Get("Type");
                //获取查询参数
                var conditions = HttpContext.Current.Server.UrlDecode(_httpReuqest.Get("conditions"));
                List<VerticaAPI.model.SearchCondition> searchCondition = null;
                //判断conditions是否为空
                if (!string.IsNullOrWhiteSpace(conditions))
                {
                    searchCondition = JsonConvert.DeserializeObject<List<VerticaAPI.model.SearchCondition>>(conditions);
                }
                if (string.IsNullOrEmpty(strtype))
                {
                    Context.Response.Write("参数错误");
                }
                var json = new StringBuilder();
                json.Append("{\"FileName\":\"" + fileName + "\",\"Type\":\"" + strtype + "\"}");

                var info = JsonConvert.DeserializeObject<ExcelInfo>(json.ToString());
                if (AllImports == null)
                    AllImports = MefConfig.ResolveMany<ExcelImport>();
                //业务类型
                var result = new ImportResult();
                var type = EnumHelper.StringToEnum<ExcelImportType>(info.Type.ToUpper());
                var handler = AllImports.FirstOrDefault(e => e.Type == type);
                if (handler == null)
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "未找到“" + type + "”相应处理模块";
                    result.Message = "未找到相应的处理模块";
                }
                var keys = GetSearchCondition(searchCondition);
                var dt = handler.GetExportData(keys);
                if (dt.Rows.Count == 0)
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "未找到可导出的数据";
                    result.Message = "无数据";
                }
                if (string.IsNullOrEmpty(info.FileName))
                {
                    info.FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls";
                }
                else
                {
                    var path = ExcelImporMapper.GetTemplatePath(type);
                    var isNeedTemp = true;
                    switch (type)
                    {
                        case ExcelImportType.STATESKC:
                        case ExcelImportType.SECONDARYDATA:
                            isNeedTemp = false;
                            break;
                        default:
                            break;
                    }
                    num++;
                    var dict = new Dictionary<string, List<string>>();
                    var gvHandler = new DwGlobalVariableHandler();
                    var yearList = gvHandler.ReturnGlobalVariableList("年份");
                    dict.Add("Yearv", yearList.Select(d => d.dictName).ToList());
                    dict.Add("Monthv", new List<string>()
                    {
                        "1",
                        "2",
                        "3",
                        "4",
                        "5",
                        "6",
                        "7",
                        "8",
                        "9",
                        "10",
                        "11",
                        "12",
                    });
                    var parentAreaList = gvHandler.ReturnGlobalVariableList("商品区域");
                    dict.Add("ParentAreaName", parentAreaList.Select(d => d.dictName).ToList());
                    //var seasonList = gvHandler.ReturnGlobalVariableList("季节");
                    dict.Add("SeasonName", new List<string>()
                    {
                        "春",
                        "夏",
                        "秋",
                        "冬",
                    });
                    var kindList = gvHandler.ReturnOdsErpSdMatKind();
                    dict.Add("KindName", kindList.Select(d => d.KindName).ToList());
                    var seriesList = gvHandler.ReturnOdsErpSdMatSeries();
                    dict.Add("SeriesName", seriesList.Select(d => d.SeriesName).ToList());
                    var filePath = info.ExportExeclToDB(dt, path, handler.DictFields, isNeedTemp, info.FileName, num,
                        dict);
                    output(filePath);
                }
            }
            catch (Exception ex)
            {
                Log.ErrorLines(ex);
            }
        }

        /// <summary>
        /// 导出Excel表格
        /// </summary>
        public void ExportExcelAll()
        {
            try
            {
                //var excelParam = _httpReuqest["excelParam"];
                var fileName = _httpReuqest.Get("FileName");
                var strtype = _httpReuqest.Get("Type");
                //获取查询参数
                var conditions = HttpContext.Current.Server.UrlDecode(_httpReuqest.Get("conditions"));
                List<VerticaAPI.model.SearchCondition> searchCondition = null;
                //判断conditions是否为空
                if (!string.IsNullOrWhiteSpace(conditions))
                {
                    searchCondition = JsonConvert.DeserializeObject<List<VerticaAPI.model.SearchCondition>>(conditions);
                }
                if (string.IsNullOrEmpty(strtype))
                {
                    Context.Response.Write("参数错误");
                }
                var fileNameStr = fileName.Split(',');
                var styleStr = strtype.Split(',');
                var jsonStr = new List<string>();
                for (var i = 0; i < fileNameStr.Length; i++)
                {
                    jsonStr.Add("{\"FileName\":\"" + fileNameStr[i] + "\",\"Type\":\"" + styleStr[i] + "\"}");
                }
                var json = "[" + jsonStr.Join(",") + "]";

                var infoStr = JsonConvert.DeserializeObject<List<ExcelInfo>>(json);
                if (AllImports == null)
                    AllImports = MefConfig.ResolveMany<ExcelImport>();
                //业务类型
                var result = new ImportResult();
                var typeStr = new List<ExcelImportType>();
                foreach (var item in infoStr)
                {
                    typeStr.Add(EnumHelper.StringToEnum<ExcelImportType>(item.Type.ToUpper()));
                }
                var handlerStr = (from ai in AllImports
                    join ts in typeStr
                    on ai.Type equals ts
                    select ai).OrderBy(d => d.Type).ToList();
                if (!handlerStr.Any())
                {
                    result.IsSuccess = false;
                    result.ExtraInfo = "未找到相应的处理模块";
                    result.Message = "未找到相应的处理模块";
                }
                var keys = GetSearchCondition(searchCondition);
                var dtStr = new List<DataTable>();
                foreach (var handler in handlerStr)
                {
                    var dt = handler.GetExportData(keys);
                    dtStr.Add(dt);
                }
                if (string.IsNullOrEmpty(infoStr[0].FileName))
                {
                    infoStr[0].FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls";
                }
                else
                {
                    var isNeedTemp = true;
                    switch (typeStr[0])
                    {
                        case ExcelImportType.STATESKC:
                        case ExcelImportType.SECONDARYDATA:
                            isNeedTemp = false;
                            break;
                        default:
                            break;
                    }
                    num++;
                    var dict = new Dictionary<string, List<string>>();
                    var gvHandler = new DwGlobalVariableHandler();
                    var yearList = gvHandler.ReturnGlobalVariableList("年份");
                    dict.Add("Yearv", yearList.Select(d => d.dictName).ToList());
                    dict.Add("Monthv", new List<string>()
                    {
                        "1",
                        "2",
                        "3",
                        "4",
                        "5",
                        "6",
                        "7",
                        "8",
                        "9",
                        "10",
                        "11",
                        "12",
                    });
                    var parentAreaList = gvHandler.ReturnGlobalVariableList("商品区域");
                    dict.Add("ParentAreaName", parentAreaList.Select(d => d.dictName).ToList());
                    //var seasonList = gvHandler.ReturnGlobalVariableList("季节");
                    dict.Add("SeasonName", new List<string>()
                    {
                        "春",
                        "夏",
                        "秋",
                        "冬",
                    });
                    var kindList = gvHandler.ReturnOdsErpSdMatKind();
                    dict.Add("KindName", kindList.Select(d => d.KindName).ToList());
                    var seriesList = gvHandler.ReturnOdsErpSdMatSeries();
                    dict.Add("SeriesName", seriesList.Select(d => d.SeriesName).ToList());
                    var filePath = infoStr[0].ExportExeclAll(dtStr, handlerStr.Select(d => d.DictFields).ToList(),
                        isNeedTemp, infoStr.Select(d => d.FileName).ToList(), num, dict);
                    output(filePath);
                }
            }
            catch (Exception ex)
            {
                Log.ErrorLines(ex);
            }
        }

        /// <summary>
        /// 获取查询参数，拼接出最终的查询条件
        /// </summary>
        /// <param name="Keys">查询条件组成的List</param>
        /// <returns>string类型的查询条件</returns>
        public string GetSearchCondition(List<VerticaAPI.model.SearchCondition> Keys)
        {
            string strWhere = string.Empty;
            if (Keys?.Count > 0)
            {
                foreach (var item in Keys)
                {
                    //判断列值是否为空，如果为空，跳过
                    if (!string.IsNullOrWhiteSpace(item.Value) && item.Value.Length > 0)
                    {
                        if (item.Operator == "like")
                        {
                            strWhere += string.Format(" {0} {1} {2} '%{3}%' ", item.Connector, item.Column, item.Operator, item.Value);
                        }
                        //店铺控件导出需要做转换
                        else if (item.Operator == "in_shopids")
                        {
                            strWhere += string.Format(" {0} {1} {2} {3} ", item.Connector, item.Column, "in", item.Value.GetString());
                        }
                        else
                        {
                            strWhere += string.Format(" {0} {1} {2} '{3}' ", item.Connector, item.Column, item.Operator, item.Value);
                        }

                    }
                }
            }
            return strWhere;
        }
    }
}